package controller.commands
{
	import com.adobe.cairngorm.business.ServiceLocator;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import flash.utils.setTimeout;
	
	import model.ModelLocator;
	
	import mx.controls.Alert;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;

	public class GetDataCommand implements ICommand
	{
		private var _service:HTTPService;
		private var _configService:HTTPService;
		private var _model:ModelLocator;
		private var _count:int = 0;;
		
		public function GetDataCommand()
		{
		}

		public function execute(event:CairngormEvent):void
		{
			_service = ServiceLocator.getInstance().getHTTPService("generic");
			_configService = ServiceLocator.getInstance().getHTTPService("config");
			_configService.addEventListener(ResultEvent.RESULT, onConfigResult);
			_configService.send();
		}
		
		private function onConfigResult(e:ResultEvent):void
		{
			//trace(_count);
			_configService.removeEventListener(ResultEvent.RESULT, onConfigResult);
			_model = ModelLocator.Instance;
			_model.storeConfig(e.result);
			_service.addEventListener(ResultEvent.RESULT, onPageResult);
			setTimeout(reload, 200);
		}
		
		private function onPageResult(e:ResultEvent):void
		{
			//trace(_count);
			_model.storePage(e.result, _count);
			
			if(_count == _model.pages.length-1)
			{
				dispose();
				return;
			} 
			reload();
		}
		
		private function reload():void
		{
			_service.url = "resources/xml/pages/" + _model.pages.getItemAt(_count).url + ".xml";
			_count++;
			//trace(_count);
			_service.send();
		}
		
		private function dispose():void
		{
			_service.removeEventListener(ResultEvent.RESULT, onPageResult);
			_configService = null;
			_service = null;
			_model = null;
			Alert.show("");
			
			
			
		}
		
	}
}